package models

import (
	"github.com/beego/beego/v2/client/orm"
	"github.com/pkg/errors"
	"time"
	"weiboxs.com/new_h_glasses/utils"
)

type DoGuahao struct {
	Id           int64     `json:"id"`
	DepartmentId int64     `json:"department_id"`
	Archives     *Archives `orm:"rel(fk);null;on_delete(do_nothing)" json:"archives"`
	CreatedAt    int64     `json:"created_at"`
	CreatedBy    string    `json:"created_by"`
	Status       int       `json:"status"` //状态0待接诊1已接诊2已退号
}

func (a *DoGuahao) TableName() string {
	return DoGuahaoTableName()
}

func DoGuahaoTableName() string {
	return TableName("do_guahao")
}

type DoGuahaoQueryParam struct {
	BaseQueryParam
	Filter       string `json:"filter"`
	StartDate    string `json:"startdate"`
	EndDate      string `json:"enddate"`
	Status       []int  `json:"status"`
	DepartmentId int64
}

//查询挂号列表
func DoGuahaoPageList(queryParam *DoGuahaoQueryParam) ([]*DoGuahao, int64) {
	query := orm.NewOrm().QueryTable(DoGuahaoTableName()).RelatedSel("Archives")
	data := make([]*DoGuahao, 0)
	cond := orm.NewCondition()
	if len(queryParam.Filter) > 0 {
		cond1 := orm.NewCondition()
		cond = cond.AndCond(cond1.Or("Archives__pinyin__contains", queryParam.Filter).Or("Archives__realname__contains", queryParam.Filter).Or("Archives__mobile__contains", queryParam.Filter))
	}
	if len(queryParam.StartDate) > 0 && len(queryParam.EndDate) > 0 {
		cond = cond.AndCond(cond.And("created_at__gte", utils.GetDateParse(queryParam.StartDate)).And("created_at__lte", utils.GetDateParse(queryParam.EndDate)+80000))
	}
	if len(queryParam.Status) > 0 {
		cond = cond.And("status__in", queryParam.Status)
	}

	sortorder := "-Id"
	switch queryParam.Sort {
	case "status":
		sortorder = "status"
	}
	if queryParam.Order == "desc" {
		sortorder = "-" + sortorder
	}
	cond = cond.And("DepartmentId", queryParam.DepartmentId)
	query = query.SetCond(cond)
	total, _ := query.Count()
	query.OrderBy(sortorder).Limit(queryParam.Limit, queryParam.Offset).All(&data)
	return data, total
}

//保存挂号
func DoGuahaoSave(model *DoGuahao) (*DoGuahao, error) {
	o := orm.NewOrm()
	format_date := utils.GetDate(time.Now().Unix())
	star := utils.GetTimeParse(format_date + " 00:00")
	end := utils.GetTimeParse(format_date + " 23:00")
	if count, _ := o.QueryTable(DoGuahaoTableName()).Filter("status__lt", 2).Filter("archives_id", model.Archives.Id).Filter("created_at__gte", star).Filter("created_at__lte", end).Count(); count > 0 {
		return nil, errors.New("今日已挂号不能重复")
	}
	model.CreatedAt = time.Now().Unix()
	if _, err := o.Insert(model); err != nil { //新增
		return nil, err
	}
	return model, nil
}

//退号
func DoGuahaoOut(guahao_id int64) error {
	if guahao_id == 0 {
		return errors.New("参数错误")
	}
	if _, err := orm.NewOrm().QueryTable(DoGuahaoTableName()).Filter("id", guahao_id).Update(orm.Params{
		"status": 2,
	}); err != nil {
		return err
	}
	return nil
}
